package com.hy.dao.impl;

import com.hy.bean.Classify;
import com.hy.dao.ClassifyDao;
import com.hy.utils.DBManager;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.math.BigDecimal;
import java.sql.Connection;
import java.util.List;

public class ClassifyDaoImpl implements ClassifyDao {
    private QueryRunner qr = new QueryRunner();

    @Override
    public List<Classify> queryAll() throws Exception {
        Connection conn = DBManager.getConnection();
        String sql = "SELECT * FROM classify ORDER BY id";
        return qr.query(conn, sql, new BeanListHandler<Classify>(Classify.class));
    }

    @Override
    public BigDecimal count(int id) throws Exception {
        Connection conn = DBManager.getConnection();
        String sql = "select count(*) from CLASSIFY c INNER JOIN GOODS g on g.CLASSIFY_ID = c.id where c.id= ?";
        BigDecimal count = qr.query(conn, sql, new ScalarHandler<BigDecimal>(),id);
        return count;
    }

    @Override
    public int insert(Classify classify) throws Exception {
        Connection conn = DBManager.getConnection();
        String sql = "INSERT INTO classify values(seq_class.nextval,?,?)";
        return qr.update(conn, sql,classify.getClassname(),classify.getRemark());
    }

    @Override
    public int insertBatch(List<Classify> entities) {
        return 0;
    }

    @Override
    public int insertOrUpdateBatch(List<Classify> entities) {
        return 0;
    }

    @Override
    public int update(Classify classify) throws Exception {
        Connection conn = DBManager.getConnection();
        String sql = "update classify set classname = ?, remark = ? where id = ?";
        return qr.update(conn, sql,classify.getClassname(),classify.getRemark(),classify.getId());
    }

    @Override
    public int deleteById(int id) throws Exception {
        Connection conn = DBManager.getConnection();
        String sql = "delete from classify where id = ?";
        return qr.update(conn, sql,id);
    }

}
